﻿using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

namespace Oliving.Edge.Common.MemoryCache
{
    /// <summary>
    /// 实例化缓存接口ICaching
    /// </summary>
    public class MemoryCaching : ICaching
    {
        //引用Microsoft.Extensions.Caching.Memory;这个和.net 还是不一样，没有了Httpruntime了
        private readonly IMemoryCache _cache;
        //还是通过构造函数的方法，获取
        public MemoryCaching(IMemoryCache cache)
        {
            _cache = cache;
        }

        public object Get(string cacheKey)
        {
            return _cache.Get(cacheKey);
        }


        public void Set(string cacheKey, object cacheValue, int cacheTime = 7200)
        {
            _cache.Set(cacheKey, cacheValue, TimeSpan.FromSeconds(cacheTime));
        }
        public void Remore(string cacheKey)
        {
            //  ((Microsoft.Extensions.Caching.Memory.MemoryCache)_cache).EntriesCollection

            //   ((Microsoft.Extensions.Caching.Memory.MemoryCache)_cache).

            List<string> keyList = GetCacheKeys("Sys_configServices");

            foreach (string keyItem in keyList)
            {
                _cache.Remove(keyItem);
            }
        }

        public void Remores(string cacheKey)
        {
            //  ((Microsoft.Extensions.Caching.Memory.MemoryCache)_cache).EntriesCollection

            //   ((Microsoft.Extensions.Caching.Memory.MemoryCache)_cache).

            List<string> keyList = GetCacheKeys(cacheKey);

            foreach (string keyItem in keyList)
            {
                _cache.Remove(keyItem);
            }
        }

        public List<string> GetCacheKeys(string strKey)
        {
            const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
            var entries = _cache.GetType().GetField("_entries", flags).GetValue(_cache);
            var cacheItems = entries as IDictionary;
            var keys = new List<string>();
            if (cacheItems == null) return keys;
            foreach (DictionaryEntry cacheItem in cacheItems)
            {
                if (cacheItem.Key.ToString().Contains(strKey))
                {
                    keys.Add(cacheItem.Key.ToString());
                }
            }
            return keys;
        }


    }

}
